<template>
  <div style="padding: 20px 20px" class="step_line">
    <el-form
      :model="ruleFormHD"
      :key="ruleFormHD.id"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      label-position="top"
      class="demo-form-inline inputForm"
      :disabled="disable"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="回单类型" prop="type">
            <el-select
              id="receipt_type_down"
              multiple
              filterable
              v-model="ruleFormHD.type"
            >
              <el-option
                id="receipt_type"
                @change="handleA"
                v-for="item in typeData"
                :label="item.value"
                :value="item.key"
                :key="item.key + ''"
                >{{ item.value }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件网点" prop="from_network_id">
            <el-select
              id="from_network_down"
              v-model="ruleFormHD.from_network_id"
              filterable
              @change="
                (val) => handleChangeNetwork(val, 'sender', 'from_network_name')
              "
            >
              <el-option
                id="from_network"
                v-for="item in websiteData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件地址" prop="senderAddress">
            <el-input
              id="from_address"
              v-model="ruleFormHD.sender.address"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发件人" prop="sender.id">
            <!-- <el-input v-model="ruleFormHD.sender.name"></el-input> -->
            <el-select
              id="sender_down"
              v-model="ruleFormHD.sender.id"
              filterable
              placeholder="请选择"
              @change="(val) => handleChangePerson(val, 'sender')"
            >
              <el-option
                id="sender"
                v-for="item in senderData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="发件人电话" prop="senderPhone">
            <el-input
              id="sender_phone"
              v-model="ruleFormHD.sender.phone"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="收件网点" prop="to_network_id">
            <el-select
              id="to_network_down"
              v-model="ruleFormHD.to_network_id"
              filterable
              @change="
                (val) => handleChangeNetwork(val, 'receiver', 'to_network_name')
              "
            >
              <el-option
                id="to_network"
                v-for="item in websiteData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收件地址" prop="returnAddress">
            <el-input
              id="to_address"
              v-model="ruleFormHD.receiver.address"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收件人" prop="receiver.id">
            <!-- <el-input v-model="ruleFormHD.receiver.name"></el-input> -->
            <el-select
              id="receiver_down"
              v-model="ruleFormHD.receiver.id"
              placeholder="请选择"
              @change="(val) => handleChangePerson(val, 'receiver')"
              filterable
            >
              <el-option
                id="receiver"
                v-for="item in senderData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id + ''"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收件人电话" prop="receiverPhone">
            <el-input
              id="receiver_phone"
              v-model="ruleFormHD.receiver.phone"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="运输类型" prop="carrier_type">
            <el-select
              id="carrier_type_down"
              v-model="ruleFormHD.carrier_type"
              @change="handleChangeCarrierType"
              filterable
              placeholder="请选择"
            >
              <el-option
                id="carrier_type"
                v-for="item in types"
                :label="item.value"
                :value="item.index"
                :key="item.index"
                >{{ item.value }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="ruleFormHD.carrier_type === '1'">
          <el-form-item label="快递公司" prop="express_id">
            <el-select
              id="collect_company_down"
              v-model="ruleFormHD.express_id"
              @change="handleChangeCompany"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                id="collect_company"
                v-for="item in companyData"
                :label="item.name"
                :value="item.id + ''"
                :key="item.id"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="ruleFormHD.carrier_type === '1'">
          <el-form-item label="快递单号" prop="express_no">
            <el-input
              id="carrier_number"
              v-model="ruleFormHD.express_no"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="mode === 'detail' || mode === 'singleDetail'">
          <el-form-item label="回单状态" prop="status">
            <el-select
              v-model="ruleFormHD.status"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in ['未签收', '已签收']"
                :label="item"
                :value="index + ''"
                :key="index"
                >{{ item }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="create_time">
            <el-date-picker
              v-model="ruleFormHD.create_time"
              clearable
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              :disabled="mode === 'edit' || mode === 'singleEdit'"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          v-if="
            ruleFormHD.status === '1' &&
            (mode === 'detail' || mode === 'singleDetail')
          "
        >
          <el-form-item label="签收时间" prop="signTime">
            <el-date-picker
              v-model="signTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="mode === 'detail' || mode === 'singleDetail'">
          <el-form-item label="操作时间" prop="update_time">
            <el-date-picker
              :value="ruleFormHD.update_time * 1000"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="回单上传" prop="uploadReceipt">
            <el-upload
              action
              :auto-upload="false"
              list-type="picture-card"
              :before-remove="beforeRemove"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :file-list="fileList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table
        :data="ruleFormHD['waybill_items']"
        class="safari_table"
        style="width: 80%"
        border
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <!-- <el-table-column label="运单号">
          <template slot-scope="scope">
            {{ scope.row["waybill_no"] }}
          </template>
        </el-table-column> -->
        <el-table-column label="回单数量" prop="count" property="count">
          <template slot="header">
            <span style="color: red">*</span> <span>回单数量</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 1px; width: 200px"
              :prop="'waybill_items.' + scope.$index + '.count'"
              :rules="rules.count"
            >
              <el-input
                id="receipt_count"
                oninput="value=value.replace(/[^\d]/g,'')"
                v-model="scope.row['count']"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="费用" prop="expense" property="expense">
          <!-- <template slot="header" v-if="rules.expense[0].required">
            <span style="color: red">*</span> <span>费用</span>
          </template> -->
          <template slot-scope="scope">
            <el-form-item
              style="margin-bottom: 1px; width: 200px"
              :prop="'waybill_items.' + scope.$index + '.expense'"
              :rules="rules.expense"
            >
              <el-input
                id="receipt_money"
                oninput="value=value.replace(/[^\d^\.]/g,'')"
                v-model="scope.row['expense']"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-row>
        <el-col :offset="18" :span="6">
          <el-form-item style="padding:20px">
            <el-button @click="cancelFn">取消</el-button>
            <el-button type="primary" @click="handleClickSubmit">保存</el-button>
          </el-form-item>
        </el-col>
      </el-row> -->
      <div
        style="margin-top: 20px; text-align: right; padding-bottom: 20px"
        v-if="!disable"
      >
        <el-button id="create_cancel" @click="cancelFn">取消</el-button>
        <el-button
          id="create_ok"
          type="primary"
          v-preventReClick
          data-tracker="P4-5"
          @click="handleClickSubmit"
          :loading="submitLoading"
          >保存</el-button
        >
      </div>
    </el-form>
    <div>
      <notify
        v-if="notifyType"
        :noTifyData="noTifyData"
        :key="noTifyData.node_id"
      ></notify>
    </div>
    <CostControl :showDialog="costDialogShow"  :overWarning="overWarning" :tableData="cost_overruns_info" @ok="handleCostOk" @close="costDialogShow=false"></CostControl>

  </div>
</template>
<script>
import {
  ReceiptAddFn,
  ReceiptEditFn,
  getConsignorList,
  getWaybillListFn,
  ReceiptDetailFn,
  reqWebsiteList,
  userList,
  carrierBox,
  FeeEntryControl,
} from "@/api/waybill";
import { timestamp10 } from "@/utils/mUtils";
import { uploading } from "../../../material/common/common";
import { parseFen, parseYuan } from "@/utils/mUtils";
import { reqStaffList } from "@/api/report";
import notify from "@/components/notify/notify.vue"; // 时间转化
import CostControl from "../costControl.vue";

export default {
  name: "addReceipt",
  data() {
    return {
      submitLoading: false,
      ruleFormHD: {
        type: [],
        sender: {
          id: "",
          name: "",
          phone: "",
          address: "",
        },
        receiver: {
          id: "",
          name: "",
          phone: "",
          address: "",
        },
        images: [],
        from_network_id: "",
        from_network_name: "",
        to_network_id: "",
        to_network_name: "",
        express_id: "",
        express_name: "",
        express_no: "",
        waybill_items: [],
        create_time: "", //创建时间
      },
      rules: {
        from_network_id: [
          { required: true, message: "请选择发件网点", trigger: "blur" },
        ],
        to_network_id: [
          { required: true, message: "请选择收件网点", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择回单类型", trigger: "change" },
        ],

        "sender.id": [
          { required: true, message: "请选择发件人", trigger: "change" },
        ],
        "receiver.id": [
          { required: true, message: "请选择收件人", trigger: "change" },
        ],
        express_id: [
          { required: true, message: "请输入快递公司", trigger: "blur" },
        ],
        express_no: [
          { required: true, message: "请输入快递单号", trigger: "blur" },
        ],
        carrier_type: [
          { required: true, message: "请选择运输类型", trigger: "change" },
        ],
        // expense: [
        //   { required: true, message: "请填写费用", trigger: "blur" },
        // ],
        count: [{ required: true, message: "请填写回单数量", trigger: "blur" }],
      },
      senderData: [],
      receiverData: [],
      websiteData: [],
      fileList: [], //上传的文件
      dialogImageUrl: "",
      dialogVisible: false,
      typeData: [
        {
          key: "0",
          value: "我司回单",
        },
        {
          key: "1",
          value: "客户单据",
        },
        {
          key: "2",
          value: "温度报告",
        },
        {
          key: "3",
          value: "其他",
        },
      ],
      companyData: [],

      types: [
        {
          index: "0",
          value: "自营",
        },
        {
          index: "1",
          value: "委外",
        },
      ],
      signTime: "",
      notifyType: false,
      noTifyData: {
        customer_id: "",
        product_type_id: "",
        node_id: "",
      },
      overWarning:"",
      cost_overruns_info:[
        ],//成本超出信息
      costDialogShow:false,
    };
  },
  props: ["formData", "mode", "ids", "id", "waybillInfo"],
  components: { notify,CostControl },

  mounted() {
    this.NotificationObj();
    if (this.mode === "edit" || this.mode === "detail") {
      this.formatData(this.formData);
    } else if (this.mode === "add") {
      this.initWaybillData();
      this.ruleFormHD.create_time = Date.now();
    }

    userList().then((res) => {
      const data = res.data || [];
      this.senderData = data.map((item) => {
        item.name = item.nickname;
        return item;
      });
      if (this.mode === "add") {
        this.ruleFormHD.sender.id = this.$store.state.user.user_id + "";
        this.handleChangePerson(this.ruleFormHD.sender.id, "sender");
      }
    });
    reqWebsiteList({}).then((res) => {
      this.websiteData = res.data;
      if (this.mode === "add") {
        this.ruleFormHD.from_network_id = this.$store.state.user.branch_id + "";
        this.handleChangeNetwork(
          this.ruleFormHD.from_network_id,
          "sender",
          "from_network_name"
        );
      }
    });
    carrierBox().then((res) => {
      this.companyData = res.data;
    });
    FeeEntryControl({}).then((res) => {
      const data = res.data || {};
      if (this.rules.expense)
        this.rules.expense[0].required =
          data.switch_status == "0" ? true : false;
      // console.log(this.rules.expense[0].required, "111111");
    });
  },
  computed: {
    disable: function () {
      return this.mode === "detail" || this.mode === "singleDetail";
    },
  },
  watch: {
    id: {
      handler: function (val) {
        val && this.getDetail();
      },
      immediate: true,
    },
  },
  methods: {
    handleNumber(value) {
      // console.log(value, "--------------q");
      value = value.replace(/[^\d^\.?]/g, "");
      // console.log(value, "--------------a");
    },
    getDetail() {
      ReceiptDetailFn({
        id: this.id + "",
        waybill_id: this.$route.query.id,
      }).then((res) => {
        const data = res.data.list[0];
        if(!data) return;
        this.formatData(data);
      });
    },
    handleChangeCompany(val) {
      const item = this.companyData.find((item) => item.id === Number(val));
      if (item) {
        this.ruleFormHD["express_name"] = item.name;
      }
    },
    formatData(formData) {
      this.ruleFormHD = formData;
      const {
        image: Images,
        sender_id,
        sender_name,
        sender_phone,
        sender_address,
        receiver_id,
        receiver_name,
        receiver_phone,
        receiver_address,
      } = formData || {};
      this.$set(this.ruleFormHD, "sender", {
        id: sender_id,
        name: sender_name,
        phone: sender_phone,
        address: sender_address,
      });
      this.$set(this.ruleFormHD, "receiver", {
        id: receiver_id,
        name: receiver_name,
        phone: receiver_phone,
        address: receiver_address,
      });

      this.ruleFormHD.id = formData.id;
      this.ruleFormHD.waybill_no = formData.waybill_no;
      this.ruleFormHD.waybill_id = formData.waybill_id;
      this.ruleFormHD.type = formData.type;
      this.ruleFormHD.express_no = formData.express_no;
      this.ruleFormHD.express_name = formData.express_name;
      this.ruleFormHD.expense = formData.expense;
      this.ruleFormHD.count = formData.count;
      this.ruleFormHD.status = formData.status;
      if (Images) {
        this.fileList = Images.map((url) => {
          return {
            url,
          };
        });
      }
      this.ruleFormHD.waybill_items = [
        {
          waybill_id: formData.waybill_id,
          waybill_no: formData.waybill_no,
          expense: parseYuan(formData.expense),
          count: formData.count,
        },
      ];
      this.ruleFormHD.images = [...this.fileList];
      this.signTime = formData.sign_time * 1000;
      this.ruleFormHD.create_time = formData.create_time * 1000;
    },
    handleCostOk(cost_overruns_info){
      this.ruleFormHD.waybill_cost_overruns_info=cost_overruns_info;
      this.handleClickSubmit()
    },
    judgeOver(res){
      if(res.data.warning){
        this.costDialogShow=true;
        this.overWarning=res.data.warning;
        this.cost_overruns_info=res.data.cost_overruns_info||[];
        this.submitLoading = false;
        return true;
      }
      return false
    },
    handleClickSubmit() {
      // if (this.ruleFormHD.status === '1' && (this.mode === 'edit' || this.mode === 'singleEdit')) {
      //   this.$message({
      //     message: "回单已签收，不能修改！",
      //     type: "warning",
      //   });
      //   return;
      // }
      // console.log(this.ruleFormHD);
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        this.submitLoading = true;
        this.ruleFormHD.images = this.ruleFormHD.images.map((item) => item.url);
        const _ruleForm = {
          ...this.ruleFormHD,
          waybill_items: JSON.parse(
            JSON.stringify(this.ruleFormHD.waybill_items)
          ),
          create_time: timestamp10(this.ruleFormHD.create_time),
        };
        _ruleForm.waybill_items.forEach((item) => {
          item.expense = parseFen(item.expense);
        });
        if (this.mode === "add") {
          ReceiptAddFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              if(this.judgeOver(res)) return;

              this.$message({
                message: "创建回单成功",
                type: "success",
              });
              this.$emit("update");
              this.$emit("updateFinish");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        } else {
          ReceiptEditFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              if(this.judgeOver(res)) return;
              this.$message({
                message: "修改回单成功",
                type: "success",
              });
              this.$emit("update");
              this.$emit("updateFinish");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        }
      });
    },
    handleA(val) {},
    handleSelectionChange() {
      // console.log("aa");
    },
    handleClose() {
      this.$emit("parentAbnormalShow", false);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //取消函数方法
    cancelFn() {
      this.$emit("update");
    },
    //确定按钮函数
    async determineFn() {
      let { ruleFormHD } = this;
      let result = await ReceiptAddFn(ruleFormHD);
    },
    // 图片上传功能
    handleChange(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      uploading(filelist, filename, type).then((res) => {
        this.ruleFormHD.images.push({
          uid: file.uid,
          url: res.res.requestUrls[0],
        });
      });
    },
    handleRemove(file, fileList) {
      const index = this.ruleFormHD.images.findIndex(
        (item) => item.uid === file.uid
      );
      index > -1 && this.ruleFormHD.images.splice(index, 1);
    },
    removeChange(file, fileList, type) {},
    handlePreview(file) {
      // this.dialogImageUrl = file.url;
      // this.dialogVisible = true;
      const regex = /\.(jpg|png|webp|jpeg)$/i;
      if (regex.test(file.url)||file.url.indexOf('blob:')==0) {
        this.$viewerApi({
          images: [file.url],
        });
      } else {
        window.open(file.url);
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChangePerson(val, type) {
      if (val) {
        const selected = this.senderData.find(
          (item) => item.id === Number(val)
        );
        if (selected) {
          this.ruleFormHD[type].id = String(selected.id);
          this.ruleFormHD[type].name = selected.name;
          this.ruleFormHD[type].phone = selected.mobile;
        }
      } else {
        this.ruleFormHD[type] = {};
      }
    },
    handleChangeCarrierType(val) {
      // 选择自营后清快递公司和快递单号数据
      if (val === "0") {
        this.ruleFormHD.express_id = "";
        this.ruleFormHD.express_name = "";
        this.ruleFormHD.express_no = "";
      } else if (val === "1") {
        this.ruleFormHD.express_id = "";
      }
    },
    handleChangeNetwork(val, type, key) {
      if (val) {
        const selected = this.websiteData.find(
          (item) => item.id === Number(val)
        );
        if (selected) {
          this.ruleFormHD[key] = selected.name;
          this.ruleFormHD[type].address = selected.address;
        }
      }
    },
    initWaybillData() {
      let { ids = "[]" } = this.$route.query || {};
      ids = JSON.parse(ids);
      const _ids = this.ids || ids.map(Number);
      getWaybillListFn({ ids: _ids }).then((res) => {
        // console.log(res, "ruleFormHDruleFormHD");
        const list = [];
        res.data.data.forEach((item) => {
          const {
            id,
            sender_name,
            fromRegion_name,
            waybill_no,
            goods = [],
          } = item;
          list.push({
            waybill_id: id,
            waybill_no,
            count: "",
            expense: "",
          });
        });
        this.ruleFormHD["waybill_items"] = list;
        this.$forceUpdate();
      });
    },
    //Notification 通知事件
    NotificationObj() {
      // console.log(this.waybillInfo, "函数调用");
      // 数据改变
      (this.noTifyData = {
        customer_id: this.waybillInfo.customer_id + "",
        product_type_id: this.waybillInfo.waybill_product_type,
        node_id: "6", //回单
      }),
        (this.notifyType = true);
    },
  },
};
</script>
